package com.realtyManage.springboot.Utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.web.multipart.MultipartFile;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;

public class OssUtil {
	private static String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
	private static String accessKeyId = "LTAIuVOmQVVpna6M";
	private static String accessKeySecret = "fY1yAntB4Tfmdcf182o5LyV7X6VE8R";
	private static String bucketName = "realty";
	String imgType = "jpg,jpeg,png,bmp,gif";
	private final String imageDir = "image";
	private final String fileDir = "file";
	private static String fileService ="https://"+bucketName +".oss-cn-hangzhou.aliyuncs.com/";//格式:bucketName.endpoint

	public Map<String, Object> upload(MultipartFile file) {
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("status", 0);
		OSSClientBuilder ossClientBuilder = new OSSClientBuilder();
		OSSClient ossClient = ossClientBuilder.build(endpoint, accessKeyId, accessKeySecret);
		if (ossClient.doesBucketExist(bucketName)) {
			// 上传到指定的文件夹
			String dir = getFileDir(file);
			String key = getTime();
			key = dir + key + "." + getFileType(file);// 加上文件后缀名
			String objectName = imageDir + "/" + key;
			try {
				ossClient.putObject(bucketName, objectName, file.getInputStream());
				result.put("status", 1);
				result.put("key", key);
			} catch (OSSException e) {
				e.printStackTrace();
			} catch (ClientException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			// 关闭连接
			ossClient.shutdown();
		} else {
			System.out.println("该区块不存在");
		}
		return result;
	}

	/**
	 * 获取文件归属文件夹
	 * 
	 * @param file
	 * @return
	 */
	public String getFileDir(MultipartFile file) {
		String fileTyle = getFileType(file).toLowerCase();
		String typeStr[] = imgType.split(",");
		for (String type : typeStr) {
			if (type.equals(fileTyle)) {
				return imageDir;
			}
		}
		return fileDir;

	}

	/**
	 * 获取文件类型
	 * 
	 * @param file
	 */
	public String getFileType(MultipartFile file) {
		String fileName = file.getOriginalFilename();
		String fileTyle = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
		return fileTyle;
	}

	/**
	 * 获取当前时间戳
	 * 
	 * @return
	 */
	public String getTime() {
		return String.valueOf(System.currentTimeMillis());
	}

	/**
	 * 只遍历file和image下的文件
	 */
	public List<Map<String, String>> getAllFile(String dirName) {
		List<Map<String, String>> result = new ArrayList<Map<String, String>>();

		// 创建链接
		OSSClientBuilder ossClientBuilder = new OSSClientBuilder();
		OSSClient ossClient = ossClientBuilder.build(endpoint, accessKeyId, accessKeySecret);

		// 构造ListObjectsRequest请求
		ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
		listObjectsRequest.setPrefix(dirName);
		// 列出Object
		ObjectListing listing = ossClient.listObjects(listObjectsRequest);
		// 遍历所有Object
		for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
			String key = objectSummary.getKey();
			Map<String, String> map = new HashMap<String, String>();
			map.put("name", key);
			if (!dirName.equals(key)) {
				// 文件
				String url = getUrl(key);
				map.put("url", url);
			} else {
				// 文件夹
				map.put("url", "#");
			}
			result.add(map);
		}
		// 关闭连接
		ossClient.shutdown();
		return result;
	}

	/**
	 * 获取文件的url
	 * 
	 * @param ossClient
	 * @param key
	 * @return
	 */
	public static String getUrl(String key) {
//		// 创建链接
//		OSSClientBuilder ossClientBuilder = new OSSClientBuilder();
//		OSSClient ossClient = ossClientBuilder.build(endpoint, accessKeyId, accessKeySecret);
//		// 获取上传文件key的url
//		GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName, key, HttpMethod.GET);
//		// 过期时间100分钟
//		Date expiration = new Date(new Date().getTime() + 1000 * 60 * 100);
//		req.setExpiration(expiration);
//		URL signedUrl = ossClient.generatePresignedUrl(req);
//		// 关闭连接
//		ossClient.shutdown();
//		System.out.println(key);
		return fileService+key;
	}

	/**
	 * 
	 * @param key
	 * @return
	 */
	public static String getUrlLongTime(String key) {
//		// 创建链接
//		OSSClientBuilder ossClientBuilder = new OSSClientBuilder();
//		OSSClient ossClient = ossClientBuilder.build(endpoint, accessKeyId, accessKeySecret);
//		// 获取上传文件key的url
//		GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName, key, HttpMethod.GET);
//		// 过期时间100年
//		Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 100);
//		req.setExpiration(expiration);
//		URL signedUrl = ossClient.generatePresignedUrl(req);
//		// 关闭连接
//		ossClient.shutdown();
		return fileService+key;
	}

	/**
	 * 删除文件
	 * 
	 * @param key
	 */
	public void deleteFile(String key) {
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		// 删除Object
		ossClient.deleteObject(bucketName, key);
		// 关闭client
		ossClient.shutdown();
	}

}
